import React, { useEffect, useRef, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { Marker } from '../types';
import './MapComponent.css';

// 从环境变量获取Mapbox token
const MAPBOX_TOKEN = import.meta.env.VITE_MAPBOX_TOKEN || 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';

mapboxgl.accessToken = MAPBOX_TOKEN;

interface MapComponentProps {
  onMarkerAdd?: (marker: Omit<Marker, 'id' | 'createdAt'>) => void;
  markers?: Marker[];
}

const MapComponent: React.FC<MapComponentProps> = ({ onMarkerAdd, markers = [] }) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const map = useRef<mapboxgl.Map | null>(null);
  const [lng, setLng] = useState(139.6917);
  const [lat, setLat] = useState(35.6895);
  const [zoom, setZoom] = useState(10);

  useEffect(() => {
    if (map.current || !mapContainer.current) return;

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v12',
      center: [lng, lat],
      zoom: zoom
    });

    map.current.on('move', () => {
      if (!map.current) return;
      setLng(Number(map.current.getCenter().lng.toFixed(4)));
      setLat(Number(map.current.getCenter().lat.toFixed(4)));
      setZoom(Number(map.current.getZoom().toFixed(2)));
    });

    // 添加点击地图事件
    map.current.on('click', (e) => {
      if (!map.current || !onMarkerAdd) return;
      
      const { lng, lat } = e.lngLat;
      
      // 创建临时标记
      new mapboxgl.Marker()
        .setLngLat([lng, lat])
        .addTo(map.current);

      // 调用回调函数
      onMarkerAdd({
        lat,
        lng,
        title: `标记点 (${lat.toFixed(4)}, ${lng.toFixed(4)})`,
        description: '用户添加的标记点'
      });
    });

    return () => {
      if (map.current) {
        map.current.remove();
        map.current = null;
      }
    };
  }, []);

  // 渲染已有的标记
  useEffect(() => {
    if (!map.current || !markers.length) return;

    // 清除现有标记
    const markersToRemove = document.querySelectorAll('.mapboxgl-marker');
    markersToRemove.forEach(marker => marker.remove());

    // 添加新标记
    markers.forEach(marker => {
      new mapboxgl.Marker()
        .setLngLat([marker.lng, marker.lat])
        .setPopup(
          new mapboxgl.Popup({ offset: 25 })
            .setHTML(`
              <h3>${marker.title}</h3>
              <p>${marker.description || '暂无描述'}</p>
              <small>坐标: ${marker.lat.toFixed(4)}, ${marker.lng.toFixed(4)}</small>
            `)
        )
        .addTo(map.current!);
    });
  }, [markers]);

  return (
    <div>
      <div className="sidebar">
        经度: {lng} | 纬度: {lat} | 缩放: {zoom}
      </div>
      <div ref={mapContainer} className="map-container" />
    </div>
  );
};

export default MapComponent;